package com.lcy.manager;

import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;
import com.lcy.exception.BusinessException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class AiManager {
//通用ai调用能力
    @Resource
    private ClientV4 clientV4;
    //稳定的随机数
    private static final Float STABLE_TEMPERATURE = 0.05f;

    //不稳定的随机数
    private static final Float UNSTABLE_TEMPERATURE = 0.99f;
    private static final int MAX_RETRIES = 3;
    private static final long INITIAL_RETRY_DELAY = 1000; // 初始重试延迟1秒


    /**
     * 异步稳定的同步请求
     * @param systemMessage 系统提示信息
     * @param userMessage 用户输入信息
     * @return 异步任务结果
     */
    @Async
    public CompletableFuture<String> doAsyncStableRequest(String systemMessage, String userMessage) {
        String result = doRequest(systemMessage, userMessage, Boolean.FALSE, STABLE_TEMPERATURE);
        return CompletableFuture.completedFuture(result);
    }



    /**
     *不稳定的同步请求
     * @param systemMessage
     * @param userMessage
     * @return
     */
    public String doSyncUnstableRequest(String systemMessage,String userMessage) {
        return doRequest(systemMessage,userMessage,Boolean.FALSE,UNSTABLE_TEMPERATURE);
    }

    /**
     *稳定的同步请求
     * @param systemMessage
     * @param userMessage
     * @return
     */
    public String doSyncStableRequest(String systemMessage,String userMessage) {
        return doRequest(systemMessage,userMessage,Boolean.FALSE,STABLE_TEMPERATURE);
    }

    /**
     *同步请求
     * @param systemMessage
     * @param userMessage
     * @param temperature
     * @return
     */
    public String doSyncRequest(String systemMessage,String userMessage,Float temperature) {
        return doRequest(systemMessage,userMessage,Boolean.FALSE,temperature);
    }

    /**
     *通用请求（简化消息传递）
     * @param systemMessage
     * @param userMessage
     * @param stream
     * @param temperature
     * @return
     */
    public String doRequest(String systemMessage,String userMessage,Boolean stream,Float temperature) {

        List<ChatMessage> chatMessageList = new ArrayList<>();
        //系统信息
        ChatMessage systemChatMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), systemMessage);
        chatMessageList.add(systemChatMessage);
        //用户信息
        ChatMessage userChatMessage = new ChatMessage(ChatMessageRole.USER.value(), userMessage);
        chatMessageList.add(userChatMessage);
        return doRequest(chatMessageList,stream,temperature);

    }

    /**
     * 通用请求
     * @param chatMessageList
     * @param stream
     * @return
     */
    public String doRequest(List<ChatMessage> chatMessageList,Boolean stream,Float temperature){


//        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
//                .model(Constants.ModelChatGLM4)
//                .stream(stream)
//                .temperature(temperature)
//                .invokeMethod(Constants.invokeMethod)//同步
//                .messages(chatMessageList)
//                .build();
//        try {
//            //获得响应
//            ModelApiResponse invokeModelApiResp = clientV4.invokeModelApi(chatCompletionRequest);
//            //获得相应结果
//            return invokeModelApiResp.getData().getChoices().get(0).toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(e.getMessage());
//        }
//
//    }
//     try {
//        ModelApiResponse response = clientV4.invokeModelApi(
//                ChatCompletionRequest.builder()
//                        .messages(chatMessageList)
//                        .temperature(temperature)
//                        .build()
//        );
//
//        // 方法一：通过JSON路径直接解析（推荐）
//        JSONObject jsonResponse = JSONObject.parseObject(JSONObject.toJSONString(response));
//        return jsonResponse.getJSONObject("data")
//                .getJSONArray("choices")
//                .getJSONObject(0)
//                .getJSONObject("message")
//                .getString("content");
//
//        // 方法二：使用SDK对象+反射（备选）
//        /*
//        Choice firstChoice = response.getData().getChoices().get(0);
//        Object message = firstChoice.getClass().getMethod("getMessage").invoke(firstChoice);
//        return (String) message.getClass().getMethod("getContent").invoke(message);
//        */
//
//    } catch (Exception e) {
//        throw new BusinessException("解析响应失败: " + e.getMessage());
//    }
//}
        int retryCount = 0;
        long retryDelay = INITIAL_RETRY_DELAY;

        while (retryCount < MAX_RETRIES) {
            try {
                ChatCompletionRequest request = buildRequest(chatMessageList, stream, temperature);
                ModelApiResponse response = clientV4.invokeModelApi(request);
                return processResponse(response);

            } catch (Exception e) {
                // 检查异常链中是否包含SocketTimeoutException
                if (isSocketTimeout(e)) {
                    retryCount++;
                    if (retryCount >= MAX_RETRIES) {
                        throw new BusinessException("AI服务请求超时，请稍后重试");
                    }
                    waitForRetry(retryCount, retryDelay, e);
                    retryDelay *= 2;
                } else {
                    throw new BusinessException("AI服务请求失败: " + e.getMessage());
                }
            }
        }
        throw new BusinessException("AI服务暂时不可用");
    }

    // 检查异常链中是否包含SocketTimeoutException
    private boolean isSocketTimeout(Throwable e) {
        while (e != null) {
            if (e instanceof SocketTimeoutException) {
                return true;
            }
            e = e.getCause();
        }
        return false;
    }

    private ChatCompletionRequest buildRequest(List<ChatMessage> messages, Boolean stream, Float temp) {
        return ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(stream)
                .temperature(temp)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .build();
    }

    private String processResponse(ModelApiResponse response) {
        if (response == null || response.getData() == null || response.getData().getChoices() == null) {
            throw new BusinessException("AI服务返回数据异常");
        }
        return response.getData().getChoices().get(0).toString();
    }

    private void waitForRetry(int retryCount, long delay, Exception e) {
        try {
            log.warn("AI服务请求超时，正在进行第{}次重试...", retryCount);
            Thread.sleep(delay);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            throw new BusinessException(5001,"请求被中断");
        }
    }
}
